<template>
    <div
        ref="commentContainer"
        :class="'comment-container flex-1 ' + (isFocus ? 'bg-white' : 'bg-f2f3f5')"
        :style="{
            border: isFocus || isBorder ? '1px #1e9fff solid' : 'none',
            backgroundColor: isFocus ? '#ffffff' : '',
        }"
    >
        <div class="w-100 flex">
            <textarea
                ref="commentText"
                v-model="content"
                placeholder="抢首评，友善交流"
                class="commentText flex-1 font-16"
                @focus="handleFocus"
                @blur="handleBlur"
                @input="handleInput"
            ></textarea>
        </div>

        <div class="pic-list">
            <div class="thumb" v-for="(item, index) in upload.fileList" :key="index">
                <img :src="getfileList(item)" />
                <span class="close" @click="delPic(item)">×</span>
            </div>
        </div>

        <div
            class="flex align-center justify-between w-100 h-40 comment-bar"
            @click="handleClickBar"
        >
            <div class="flex align-center mar-l-10">
                <div class="mar-r-2vw cur-pointer hoverClass color-999999 font-22">
                    <SvgIcons iconClass="emoji_icon" />
                </div>

                <el-upload
                    ref="uploadCommentImg"
                    :disabled="upload.fileList.length === 1"
                    :action="upload.action"
                    :name="upload.name"
                    :accept="upload.accept"
                    :limit="upload.limit"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="handleFileSuccess"
                    :on-error="handleFileError"
                    :on-progress="handleFileProgress"
                >
                    <template slot="trigger">
                        <SvgIcons iconClass="photo_icon" class="cur-pointer hoverClass color-999999 font-18 mar-r-2vw" />
                    </template>
                </el-upload>
            </div>

            <div class="flex align-center">
                <div class="mar-r-2vw">
                    <span class="color-666666">{{ count }}</span>
                    <span class="color-999999"> /{{ maxCount }}</span>
                </div>

                <el-tooltip class="item" effect="dark" content="标点符号、链接等计算在有效字数内" placement="bottom">
                    <SvgIcons iconClass="about_icon" class="cur-pointer hoverClass color-999999 font-18 mar-r-2vw" />
                </el-tooltip>

                <el-button
                    class="mar-r-10"
                    type="primary"
                    size="small"
                    :disabled="!content"
                    @click="handleSendComment()"
                >
                    发送
                </el-button>
            </div>
        </div>
    </div>
</template>

<script>
    import SvgIcons from '@/components/SvgIcons/index'
    import Utils from '@/utils/utils'
    import { mapState } from 'vuex'

    export default {
        components: {
            SvgIcons,
        },

        computed: {
            ...mapState({
				token: state => state.user.token,
			}),

            // 上传照片请求头
            uploadHeaders() {
                return {
                    'Authorization': 'Bearer ' + this.token
                }
            },

            // 获取图片地址
			getfileList() {
				return (item) => {
					return process.env.VUE_APP_IMG_BASE_API + item.url
				}
			},
        },

        data() {
            return {
                content: '', // 一级评论内容
				isFocus: false, // 是否获取焦点
				isBorder: false, // 是否显示边框
                count: 0, // 字数
				maxCount: 1000, // 最大字数

                // 上传
                upload: {
                    action: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PROD_UPLOAD_BASE_API : process.env.VUE_APP_PROD_UPLOAD_BASE_API,
                    name: 'file',
                    accept: '.jpg,.png,.jpeg,.gif,.bmp',
                    limit: 1,
                    fileList: [],
                },
            }
        },

        methods: {
            // 删除图片
			delPic(idx) {
				this.upload.fileList.splice(idx, 1)
			},

			// 文件上传成功
            handleFileSuccess(response, file) {
                this.pageLoading.close()

                if (response.code === 200) {
                    this.upload.fileList.push(response.data)
                    Utils.popUpMsg('success', response.msg, 1500)
                } else {
                    Utils.popUpMsg('error', response.msg, 3000)
                }

                this.$refs.uploadCommentImg.clearFiles()
            },

            // 文件上传错误
            handleFileError(error, file) {
                this.pageLoading.close()
                this.$refs.uploadCommentImg.clearFiles()
            },

            // 文件上传时
            handleFileProgress(event,file) {
                this.pageLoading = Utils.loading('图片上传中...')
            },

			// 当获取焦点时的回调
			handleFocus() {
				let commentText = this.$refs.commentText

				if (this.isFocus) {
					this.childNode = null
					return
				}

				// 执行一次
				commentText.animate([
					{ height: '50px' },
					{ height: '150px' }
				], {
					duration: 200,
					fill: 'forwards'
				})

				this.isFocus = true
			},

            // 当点击评论框时
			handleClickBar(e) {
				this.childNode = e.target
			},

            // 当失去焦点时的回调
			handleBlur() {
				let commentText = this.$refs.commentText
				let parentNode = this.$refs.commentContainer
				
				setTimeout(() => {
					if (parentNode.contains(this.childNode)) {
						return
					}

					this.isBorder = this.content ? true : false
					this.isFocus = false

					// 执行一次
					commentText.animate([
						{ height: '150px' },
						{ height: '50px' }
					], {
						duration: 200,
						fill: 'forwards'
					})

					this.parentNode = null
					this.childNode = null
				}, 200)
			},

            // 当输入框内容输入时的回调
			handleInput(e) {
				let commentText = e.target.value
				let len = commentText.length

				if (len > this.maxCount) {
					this.content = commentText.substring(0, this.maxCount)
				} else {
					this.content = commentText
				}

				this.count = this.content.length
			},

            // 发送评论
            handleSendComment() {
                let picUrls = this.upload.fileList.map(item => item.url).join(',')
                this.$emit('handleSendComment', { content: this.content, picUrls })
            },

            // 清空数据
            clearData() {
                this.content = ''
                this.upload.fileList = []
            },
        }
    }
</script>

<style lang="scss" scoped>
    .comment-container {
		box-sizing: border-box;
		border-radius: 5px;
		transition-property: background-color;
		transition-duration: 0.7s;
	}

	.comment-container:hover {
		background-color: #e4e6eb;
	}

    .comment-container .commentText {
		height: 50px;
		outline: none;
		border: none;
		border-radius: 5px;
		padding: 10px;
		box-sizing: border-box;
		resize: none;
		background: none;
    }

	.comment-container .commentText::placeholder {
		font-family: '苹方';
		font-size: 16px;
		color: #999999;
	}

	.comment-container .comment-bar {
		margin-top: 5px;
		border-bottom-right-radius: 5px;
		border-bottom-left-radius: 5px;
	}

    .pic-list {
		display: flex;
		gap: 8px;
		overflow-x: auto;
		align-items: flex-start;
	}

	.thumb {
		position: relative;
		flex-shrink: 0;
		width: 100px;
		height: auto;
		margin-left: 10px;
	}

	.thumb img {
		width: 100px;
		height: auto;
		object-fit: cover;
		border-radius: 4px
	}

	.close {
		position: absolute;
		top: 1px;
		right: 1px;
		background: #000;
		color: #fff;
		border-radius: 50%;
		width: 18px;
		height: 18px;
		line-height: 18px;
		text-align: center;
		cursor: pointer;
		font-size: 12px
	}
</style>
